using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Xml;
using IWCommunity.Common;

namespace IWCommunity.Blogs.WebControls
{
    /// <summary>
    /// Designed to return list of all discussion lists from current Web.
    /// </summary>
    public class ForumsList : List
    {
        protected override System.Xml.XmlDocument BuildDocument()
        {
            try
            {

                XmlDocument oDoc = new XmlDocument();
                oDoc.LoadXml("<rows/>"); //add outer element called rows

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite ElevatedSiteCollection = new SPSite(SPContext.Current.Web.Site.ID))
                    {
                        using (SPWeb ElevatedSite = ElevatedSiteCollection.OpenWeb(Web.ID))
                        {

                            //get all discussion lists
                            SPListCollection discLists = ElevatedSite.Lists; //tried GetListsOfType(SPBaseType.DiscussionBoard), but it returns nothing???weird

                            for (int i = 0; i < discLists.Count - 1; i++) //loop through each list
                            {
                                SPList list = discLists[i];
                                if (list.BaseTemplate.ToString().ToLower() == "discussionboard")
                                {
                                    XmlElement rowNode = oDoc.CreateElement("row"); //add inner element called row
                                    //add appropriate attrributes
                                    rowNode.SetAttribute("listTitle", list.Title);
                                    rowNode.SetAttribute("listDesc", list.Description);
                                    rowNode.SetAttribute("listItems", list.ItemCount.ToString());
                                    rowNode.SetAttribute("listUrl", list.DefaultViewUrl);
                                    rowNode.SetAttribute("listLastUpdated", list.LastItemModifiedDate.ToString("dd-MM-yy hh:mmmm:ss"));

                                    //TODO:add thread count
                                    oDoc.DocumentElement.AppendChild(rowNode);
                                }

                            }
                        }//end using SpWeb
                    } //end using spsite
                });//end spsecurity
                return oDoc;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex); //log error
                XmlDocument oError = new XmlDocument();
                oError.LoadXml(string.Format("<Error>{0}</Error>", ex.Message));
                return oError;
            }
        }
    }
}
